#!/usr/bin/perl -w
use Env qw(HOME);
# this srcipt requires that you have the query sequence as a *.fas file and the database as "wholedb/repdb"
my $database = "$HOME/project/cell_wall/db/repdb";
my $directory = shift @ARGV || ".";
opendir(DIR, $directory) || die "cannot open $directory: $!";

for my $file (readdir(DIR) ) {
 next unless ( $file =~ /(\S+)\.fas$/);
 my $base = $1;
 print "Processing file: $file ($base)\n";
 `/usr/local/bin/jackhmmer-3.0b3 --tblout $base.out --chkhmm $base --chkali $base --incE 1e-5 $file $database > $base.jackhmmer`;
 `perl $HOME/project/stajichlab/labcode/cell_wall/scripts/hmmer3_filter.pl --db $database $base.out > $base\_hits.pep`;
  # get the largest HMM number
  opendir(REOPENDIR,$directory) || die "cannot open $directory for reopening: $!";
  my $num = 0;
  for my $hmm ( readdir(REOPENDIR) ) {
    if( $hmm =~ /$base-(\d+)\.hmm$/ ) {
      my $seen_num = $1;
      if( $seen_num > $num ) { $num = $seen_num }
    }
   }
   closedir(REOPENDIR);
   `/usr/local/bin/hmmalign-3.0b3 $base-$num.hmm $base\_hits.pep > $base\_hits.sto`;
   `perl ~jstajich/scripts/selex2fasaln.pl $base\_hits.sto > $base\_hits.fasaln 2>errors.ignore`;
   `/usr/local/bin/bp_sreformat.pl -if fasta -of nexus --special="mrbayes" -i $base\_hits.fasaln -o $base\_hits.nex`;
#the .nex file needs to be modified to include the parameters
   `cat $HOME/projects/stajichlab/labcode/cell_wall/mrbayes_block.nex >> $base\_hits.nex`;
   print "starting tree building\n";
 `~jstajich/bin/mb $base\_hits.nex >& $base.log `;
}
